<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<script type="text/javascript">
    $.fn.serializeObject = function(){
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    function addrows(){
        var tbIdx = 0;
        if (typeof($("#contentTableU tbody tr:last").attr('xia')) == 'undefined') {
            tbIdx = 0;
        } else {
            tbIdx = Number($("#contentTableU tbody tr:last").attr('xia')) + 1;
        }

        var drugCode = $('#drugCode').val();
        var drugName = $('#drugName').val();
        if(drugCode == null || drugCode == '' || typeof(drugCode) == 'undefined' || drugName == null || drugName == '' || typeof(drugName) == 'undefined'){
            toastr.error('没有要添加的数据!');
            return ;
        }
        if($('#plannedSelling').val() == null || $('#plannedSelling').val() == "" || typeof($('#plannedSelling').val()) == "undefined"){
            toastr.error("请输入计划数量!");
            return ;
        }
        var list = $("table tr").find("td:eq(0)");
        var jsonuserinfo= $("#inputForm").serializeObject();
        var datastr = JSON.stringify(jsonuserinfo);
        var trHTML = "<tr xia='" + tbIdx + "'>";
        trHTML += "<td hidden>"+ datastr +"</td>";
        trHTML += "<td hidden><input name='drugBuyPlanList[" + tbIdx + "].id' value=''" + "/></td>";
        trHTML += "<td hidden><input name='drugBuyPlanList[" + tbIdx + "].stateFlag' value='1'" + "/></td>";
        trHTML += "<td hidden><input id='infoId"+ tbIdx +"' name='drugBuyPlanList[" + tbIdx + "].infoId' value='"+ $('#infoId').val() +"'/></td>";
        trHTML += "<td hidden>"+ (tbIdx + 1) + "<input type='hidden' id='purchaseOrder"+ tbIdx +"' name='drugBuyPlanList[" + tbIdx + "].purchaseOrder' value='"+ (tbIdx + 1) +"'/></td>";
        trHTML += "<td hidden><input id='purchaseNumber"+ tbIdx +"' name='drugBuyPlanList[" + tbIdx + "].purchaseNumber' value='"+ $('#purchaseNumber').val() +"'/></td>";
        trHTML += "<td>"+ $('#drugCode').val() + "<input type='hidden' name='drugBuyPlanList[" + tbIdx + "].drugCode' value='" + $('#drugCode').val() + "'/></td>";
        trHTML += "<td>"+ $('#drugName').val() + "<input type='hidden' name='drugBuyPlanList[" + tbIdx + "].drugName' value='" + $('#drugName').val() + "'/></td>";
        trHTML += "<td>"+ $('#packageNum').val() + "<input type='hidden' name='drugBuyPlanList[" + tbIdx + "].drugStock.drugInfo.packageNum' value='" + $('#packageNum').val() + "'/></td>";
        trHTML += "<td>"+ $('#packageSpec').val() + "<input type='hidden' name='drugBuyPlanList[" + tbIdx + "].packageSpec' value='" + $('#packageSpec').val() + "'/></td>";
        trHTML += "<td hidden>"+ $('#packageUnits').val() + "<input type='hidden' name='drugBuyPlanList[" + tbIdx + "].packageUnit' value='" + $('#packageUnits').val() + "'/></td>";
        trHTML += "<td>"+$('#packageUnit').val() +"</td>";
        trHTML += "<td hidden>"+ $('#drugFrom').val() +"<input name='drugBuyPlanList[" + tbIdx + "].drugForm' value='"+ $('#drugFrom').val() +"'/></td>";
        trHTML += "<td hidden>" + $('#drugSupplierCataId').val() + "<input type='hidden' name='drugBuyPlanList[" + tbIdx + "].vedorName' value='" +
        $('#drugSupplierCataId').val() + "'/></td>";
        trHTML += "<td>"+$('#supplierJc').val() +"</td>";
        trHTML += "<td><input id='costPrice"+ tbIdx +"' name='drugBuyPlanList[" + tbIdx + "].costPrice' onchange=\"changeFun('costPrice'," + tbIdx + ")\" class='form-control' width='20px' value='" +
        $('#tradePrice').val() + "'></td>";
        trHTML += "<td><input id='selling"+ tbIdx +"' name='drugBuyPlanList[" + tbIdx + "].plannedSelling' onchange=\"changeFun('selling'," + tbIdx +")\" class='form-control' width='20px' value='" + $('#plannedSelling').val() + "'/></td>";
        trHTML += "<td><input id='amount" + tbIdx + "' name='drugBuyPlanList[" + tbIdx + "].plannedAmount' readonly class='form-control' width='20px' value='" + $('#plannedAmount').val() + "'/></td>";
        trHTML += "<td><input type='hidden' name='drugBuyPlanList[" + tbIdx + "].warehouseKeeper' value=''/></td>";
        trHTML += "<td>"+$('#stockQuantity').val() +"</td>";
        trHTML += "<td>"+$('#monthUsed').val() +"</td>";
        trHTML += "<td><a href='#' onclick='removeList("+ tbIdx +",this)' class='applyBt btn btn-danger btn-xs'>删除</a></td>"
        trHTML += "</tr>";
        $("#inputForm input").val("");
        $("#contentTableU").append(trHTML);
        return loadDiv('rigthCenterDiv','${ctx}/drug/buyPlanAudit/updatePlanForm');
    }

    //表单自动回填的方法
    var fillForm = function($form, json) {
        var jsonObj = json;
        if (typeof json === 'string') {
            jsonObj = $.parseJSON(json);
        }
        for ( var key in jsonObj) { // 遍历json字符串
            var objtype = jsonObjType(jsonObj[key]); // 获取值类型
            if (objtype === "array") { // 如果是数组，一般都是数据库中多对多关系
                var obj1 = jsonObj[key];
                for ( var arraykey in obj1) {
                    // alert(arraykey + jsonObj[arraykey]);
                    var arrayobj = obj1[arraykey];
                    for ( var smallkey in arrayobj) {
                        setCkb(key, arrayobj[smallkey]);
                        break;
                    }
                }
            } else if (objtype === "object") { // 如果是对象，啥都不错，大多数情况下，会有 xxxId
                // 这样的字段作为外键表的id

            } else if (objtype === "string") { // 如果是字符串
                var str = jsonObj[key];
                var date = new Date(str);
                if (date.getDay()) { // 这种判断日期是本人懒，不想写代码了，大家慎用。
                    $("[name=" + key + "]", $form).val(str);
                    continue;
                }

                var tagobjs = $("[name=" + key + "]", $form);
                if ($(tagobjs[0]).attr("type") == "radio") {// 如果是radio控件
                    $.each(tagobjs, function(keyobj, value) {
                        if ($(value).attr("val") == jsonObj[key]) {
                            value.checked = true;
                        }
                    });
                    continue;
                }
                $("[name=" + key + "]", $form).val(jsonObj[key]);
            } else { // 其他的直接赋值
                $("[name=" + key + "]", $form).val(jsonObj[key]);
            }

        }
    }

    var setCkb = function(name, value) {
        // alert(name + " " + value);
        // $("[name=" + name + "][value=" + value + "]").attr("checked", "checked");
        // 不知为何找不到具体标签;
        $("[name=" + name + "][val=" + value + "]").attr("checked", "checked");
    }

    var fillckb = function(name, json) {
        var jsonObj = json;
        if (typeof json === 'string') {
            jsonObj = $.parseJSON(json);
        }
        var str = jsonObj[name];
        if (typeof str === "string") {
            var array = str.split(",");
            $.each(array, function(key, value) {
                setCkb(name, value);
            });
        }
    }

    var jsonObjType = function(obj) {
        if (typeof obj === "object") {
            var teststr = JSON.stringify(obj);
            if (teststr[0] == '{' && teststr[teststr.length - 1] == '}')
                return "class";
            if (teststr[0] == '[' && teststr[teststr.length - 1] == ']')
                return "array";
        }
        return typeof obj;
    }
    //表单回填EN
</script>
<div class="content-wrap">
    <div class="wrapper" style="bottom: 50px;">
        <ul class="nav nav-tabs">
            <li>
                <a href="#"  onclick="loadDiv('rigthCenterDiv','${ctx}/drug/buyPlanAudit/createPlanForm')">增加采购明细</a>
            </li>
        </ul>
        <section class="panel panel-default">
            <div class="panel-body">
                <div class="col-lg-12">
                    <form:form id="inputForm" data-parsley-validate=""  modelAttribute="drugBuyPlan" class="form-horizontal">
                    <form:hidden path="id" id="id"/>
                    <form:hidden path="infoId" id="infoId"/>
                    <form:hidden path="purchaseNumber" id="purchaseNumber"/>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">药品编码：</label>
                        <div class="col-sm-8">
                            <form:input path="drugCode" id="drugCode" htmlEscape="false" class="form-control" maxlength="32" readonly="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">药品名称：</label>
                        <div class="col-sm-8">
                            <form:input path="drugName" id="drugName" htmlEscape="false" class="form-control"  maxlength="64" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">包装数量：</label>
                        <div class="col-sm-8">
                            <form:input path="drugStock.drugInfo.packageNum" id="packageNum" htmlEscape="false" class="form-control"  maxlength="8" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">包装规格：</label>
                        <div class="col-sm-8">
                            <form:input path="packageSpec" id="packageSpec" htmlEscape="false" class="form-control"  maxlength="20" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">包装单位：</label>
                        <div class="col-sm-8">
                            <form:hidden path="drugStock.drugInfo.packageUnit" id="packageUnits" />
                            <form:input path="packageUnit" id="packageUnit" htmlEscape="false" class="form-control"  maxlength="2" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">最小规格：</label>
                        <div class="col-sm-8">
                            <form:input path="drugStock.drugInfo.minSpec" id="minSpec" htmlEscape="false" class="form-control"  maxlength="20" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">最小单位：</label>
                        <div class="col-sm-8">
                            <form:input path="drugStock.drugInfo.minUnits" id="minUnits" htmlEscape="false" class="form-control"  maxlength="2" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">剂&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;型：</label>
                        <div class="col-sm-8">
                            <form:hidden path="drugForm" id="drugFromCode" />
                            <form:select path="drugNameDict.drugFrom" id="drugFrom" htmlEscape="false" class="form-control" maxlength="1" data-parsley-required="true" disabled="true">
                                <form:options items="${fns:getDictList('DRUG_FORM_DICT')}" itemLabel="label" itemValue="value" htmlEscape="false" />
                            </form:select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">厂&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;家：</label>
                        <div class="col-sm-8">
                            <form:hidden path="vedorName" id="drugSupplierCataId" />
                            <form:input path="drugStock.drugInfo.drugSupplierCata.supplierJc" id="supplierJc" htmlEscape="false" class="form-control"  maxlength="64" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">批&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;价：</label>

                        <div class="col-sm-8">
                            <form:input path="costPrice" id="tradePrice" htmlEscape="false" class="form-control" readonly="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">售&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;价：</label>
                        <div class="col-sm-8">
                            <form:input path="drugPrice.retailPrice" id="retailPrice" htmlEscape="false" class="form-control" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">计划数量：</label>
                        <div class="col-sm-8">
                            <form:input path="plannedSelling" id="plannedSelling" htmlEscape="false" class="form-control" onchange="updatePlannedAmount()"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">计划金额：</label>
                        <div class="col-sm-8">
                            <form:input path="plannedAmount" id="plannedAmount" htmlEscape="false" class="form-control" readonly="true"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">当前库存：</label>
                        <div class="col-sm-8">
                            <form:input path="drugStock.quantity" id="stockQuantity" htmlEscape="false" class="form-control" readonly="true" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">月消耗量：</label>
                        <div class="col-sm-8">
                            <form:input path="monthUsed" id="monthUsed" htmlEscape="false" class="form-control" readonly="true"/>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <input id="btnSubmit" class="btn btn-primary" type="submit" value="确 定" onclick="addrows()">&nbsp;
                        <input id="btnCancel" class="btn" type="button" value="关 闭" onclick="closeRight()"></div>
                </div>
                </form:form>
            </div>
        </section>
    </div>
</div>

<script>
    /*药品自动补全*/
    autoCompleteDrugPrice("drugName");
    function autoCompleteDrugPrice(inputId){
        var url="${ctx}/drug/buyPlanAudit/autoBuyPlanDrugInfo";
        autoComplete(inputId,url,
                function(data){
                    var rows = [];
                    for(var i=0; i<data.length; i++){
                        rows[rows.length] = {
                            data:data[i],
                            value:data[i].id,
                            result:data[i].drugName
                        };
                    }
                    return rows;
                },function(data, i, max){
                    return data.drugName+"|"+"|"+data.packageSpec+"|"+data.drugStock.drugInfo.drugSupplierCata.supplierJc+"|"+data.drugStock.quantity+data.packageUnit;
                },function(event,data,formatted){
                    var purchaseNumber = '';
                    $("#contentTableU tbody tr").each(function (index,item) {
                        var xia = $(this).attr("xia");
                        var infoId = $('#infoId' + xia).val();
                        purchaseNumber = $('#purchaseNumber' + xia).val();
                        if(data.infoId == infoId){
                            toastr.error('列表中该规格的药品已经存在,请重新选择!');
                            addBuyPlanItem();
                            return ;
                        }
                    });
                    $('#infoId').attr('value',data.infoId);
                    $('#purchaseNumber').attr('value', purchaseNumber);
                    $('#drugCode').attr('value',data.drugCode);
                    $('#drugName').attr('value',data.drugName);
                    $('#packageNum').attr('value',data.drugStock.drugInfo.packageNum);
                    $('#packageSpec').attr('value', data.packageSpec);
                    $('#packageUnits').attr('value', data.drugStock.drugInfo.packageUnit);  //包装单位代码
                    $('#packageUnit').attr('value', data.packageUnit);
                    $('#minSpec').attr('value', data.drugStock.drugInfo.minSpec);
                    $('#minUnits').attr('value', data.drugStock.drugInfo.minUnits);
                    $('#drugFrom').val(data.drugNameDict.drugFrom);
                    $('#drugFromCode').val(data.drugNameDict.drugFrom);  //剂型代码
                    $('#drugSupplierCataId').attr('value',data.drugStock.drugInfo.drugSupplierCata.id);  //厂家ID
                    $('#supplierJc').attr('value', data.drugStock.drugInfo.drugSupplierCata.supplierJc);
                    $('#tradePrice').attr('value',data.drugPrice.tradePrice);
                    $('#retailPrice').attr('value',data.drugPrice.retailPrice);
                    $('#stockQuantity').attr('value',data.drugStock.quantity);
                });
    }

    //根据输入的计划数量计算计划金额
    function updatePlannedAmount(){
        var plannedSelling = parseFloat($('#plannedSelling').val());
        var tradePrice = parseFloat($('#tradePrice').val());
        var plannedAmount = plannedSelling * tradePrice;
        $('#plannedAmount').attr('value', Math.round(plannedAmount*100)*1000/1000/100);
    }

    //关闭右侧添加药品明细页面
    function closeRight(){
        $("#drugPlanRightDiv").attr("style","display: none");
        $("#drugBuyPlanUpdateDiv").attr("class","main-content col-lg-12");
        $("#drugBuyPlanUpdateDiv").show('normal');
    }
</script>